#include "stdafx.h"
#include "render/rendermgr.h"
#include "./statmgr.h"

#define WAIT_TIME 1.5

StatMgr::StatMgr()
: m_playerCount(0)
, m_minPlayerCount(0)
, m_waitTime(0)
, m_bStartCalc(false)
{

}

StatMgr::~StatMgr()
{

}

void StatMgr::Start()
{
	RenderMgr::GetInstance().OnAfterRender += EventObject<OnAfterRenderFunc>(this, &StatMgr::OnAfterRender);
}

void StatMgr::Stop()
{
	RenderMgr::GetInstance().OnAfterRender -= EventObject<OnAfterRenderFunc>(this, &StatMgr::OnAfterRender);
	m_playerCount = 0;
	m_waitTime = 0;
	m_bStartCalc = false;
}

void StatMgr::SetMinPlayerCount(int minPlayerCount)
{
	m_minPlayerCount = minPlayerCount;
}

void StatMgr::AddPlayer(string strName, Color color)
{
	StatData& statData = m_statDatas[m_playerCount++];
	statData.strName = strName;
	statData.color = color;
	statData.bulletCount = 0;
	memset(statData.hittedCount, 0, sizeof(int) * MAX_PLAYER_COUNT);
}

void StatMgr::AddBullet(int id)
{
	StatData& statData = m_statDatas[id];
	statData.bulletCount++;
}

void StatMgr::Impacted(int id, int hittedId)
{
	StatData& statData = m_statDatas[id];
	if (hittedId == -1)
	{
		statData.hittedCount[4]++;
	}
	else
	{
		statData.hittedCount[hittedId]++;
	}
}

void StatMgr::OnAfterRender(float differTime)
{
	if (m_bStartCalc)
	{
		m_waitTime += differTime;

		if (m_waitTime >= WAIT_TIME)
		{
			FireEvent(OnStatEndFunc, OnStatEnd, (m_playerCount, m_statDatas));
			Stop();
		}
		return;
	}

	int leftcount = 0;

	vector<Player*>& playerlist = PlayerMgr::GetInstance().GetPlayers();
	for (size_t i = 0; i < playerlist.size(); ++i)
	{
		if (!playerlist[i]->GetDestroyed())
		{
			leftcount++;
		}
	}

	if (leftcount <= m_minPlayerCount)
	{
		m_bStartCalc = true;
	}
}